package com.yokead.service.order;

import cn.hutool.core.date.DateUtil;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import cn.simplifydb.database.base.BaseRead;
import cn.simplifydb.database.run.read.SelectPage;
import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.database.DatabaseContextHolder;
import com.yokead.i.CoverInfo;
import com.yokead.service.BaseService;
import com.yokead.system.log.LogType;
import com.yokead.system.log.SystemLog;
import com.yokead.util.JsonUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by jiangzeyin on 2017/5/17.
 */
@Service
public class OrderService extends BaseService {

    @Resource
    private ProductService productService;

    public String zf(String tableName, String id, String ids, int dataType) {
        if (dataType > 1 || dataType < 0) {
            dataType = 1;
        }
        if (tableName == null) {
            return JsonMessage.getString(410, "作废失败，请检查使用方式");
        }
        int id_int = StringUtil.parseInt(id, -1);
        if (id_int <= 0 && StringUtil.isEmpty(ids)) {
            return JsonMessage.getString(400, "请检查使用方式");
        }
        String inId;
        if (id_int > 0) {
            inId = String.valueOf(id_int);
        } else {
            String tempIds = ids.replace(",", "");
            char[] chars = tempIds.toCharArray();
            for (char item : chars) {
                if (!Character.isDigit(item)) {
                    return JsonMessage.getString(400, "请检查使用方式,包含非法字符");
                }
            }
            inId = ids;
        }
        String sql = String.format("update %s set isDelete=%s,modifyTime=UNIX_TIMESTAMP(NOW()) where id in(%s)", tableName, dataType, inId);
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        try {
            SystemLog.LOG(LogType.SQL).info(sql);
            JdbcUtils.executeUpdate(dataSource, sql);
        } catch (SQLException e) {
            SystemLog.LOG(LogType.SQL_ERROR).error("查询失败", e);
            return JsonMessage.getString(410, "作废失败，请稍后再来");
        }
        return JsonMessage.getString(200, "作废成功");
    }

    /**
     * 查询广告数据
     *
     * @param name
     * @param product
     * @param pageNo
     * @param pageSize
     * @return
     */
    public String doSelect(String name, String product, int pageNo, int pageSize, String gzid, int dataType, String date, String product_name, HashMap<String, CoverInfo> coverInfoHashMap) {
        if (dataType > 1 || dataType < 0) {
            dataType = 0;
        }
        String tableName;
        try {
            tableName = productService.getProductTableName(name, product);
        } catch (IOException e) {
            SystemLog.ERROR().error("获取失败", e);
            return JsonMessage.getString(100, "获取失败");
        }
        JSONObject jsonObject = getProductColumn(name, product);
        if (jsonObject == null) {
            return JsonMessage.getString(102, "获取失败,null");
        }
        int pageNo_int = StringUtil.parseInt(pageNo, 1);
        int pageSize_int = StringUtil.parseInt(pageSize, 10);
        String sqlColumn = jsonObject.getString("sqlColumn");
        SelectPage<?> selectPage = new SelectPage<>();
        String sql = String.format("select %s from %s", sqlColumn, tableName);
        selectPage.setSql(sql);
//        Page<?> page = new Page();
        selectPage.setPageNoAndSize(pageNo_int, pageSize_int);
        selectPage.where("isDelete=" + dataType);
        if (!StringUtil.isEmpty(date)) {
            String[] dates = StringUtil.stringToArray(date, "_");
            if (dates == null || dates.length < 2) {
                return JsonMessage.getString(103, "时间选择不正确");
            }
            try {

                int startTime = (int) (DateUtil.parse(dates[0], "yyyy-MM-dd").getTime() / 1000L);
                int endTime = (int) ((int) (DateUtil.parse(dates[1], "yyyy-MM-dd").getTime() / 1000L) + TimeUnit.HOURS.toSeconds(24));

                selectPage.whereAnd("createTime>=" + startTime + " and createTime<=" + endTime);
            } catch (Exception e) {
                SystemLog.ERROR().error("时间格式不正确:" + date, e);
                return JsonMessage.getString(103, "时间格式不正确");
            }
        }
        if (!StringUtil.isEmpty(product_name) && !"全部".equals(product_name)) {
            selectPage.whereAnd("product='" + product_name + "'");
        }
        // do gid
        if (StringUtil.isEmpty(gzid) || "全部".equals(gzid)) {
            //
        } else if ("默认".equals(gzid)) {
            selectPage.whereAnd("(gid is null or gid='')");
        } else {
            selectPage.whereAnd("gid='" + gzid + "'");
        }
        selectPage.orderBy("createTime desc");
        // Page page1 = new Page();
        selectPage.setTag("core");
        selectPage.setResultType(BaseRead.Result.PageResultType);
        JSONObject result = selectPage.run();
        if (coverInfoHashMap != null) {
            JSONArray results = result.getJSONArray("results");
            if (results != null) {
                for (Object object : results) {
                    JSONObject item = (JSONObject) object;
                    Set<String> set = coverInfoHashMap.keySet();
                    for (String setKey : set) {
                        String value = item.getString(setKey);
                        CoverInfo coverInfo = coverInfoHashMap.get(setKey);
                        value = coverInfo.doStr(value);
                        item.put(setKey, value);
                    }
                }
                result.put("results", results);
            }
        }
        return JsonMessage.getString(200, "获取成功", result);
    }

    public String getProduct(String name, String product) {
        String tableName;
        try {
            tableName = productService.getProductTableName(name, product);
        } catch (IOException e) {
            SystemLog.ERROR().error("查询失败", e);
            return JsonMessage.getString(100, "获取失败");
        }
        if (StringUtil.isEmpty(tableName)) {
            return JsonMessage.getString(100, "没有对应产品信息");
        }
        String sql = String.format(" SELECT product FROM %s where isDelete =0 GROUP BY product", tableName);
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        SystemLog.LOG(LogType.SQL).info(sql);
        JSONArray jsonArray = new JSONArray();
        try {
            List<Map<String, Object>> list = JdbcUtils.executeQuery(dataSource, sql);
            if (list != null) {
                for (Map<String, Object> map : list) {
                    String gid = StringUtil.convertNULL(map.get("product"));
                    if (StringUtil.isEmpty(gid)) {
                        continue;
                    }
                    if (!jsonArray.contains(gid)) {
                        jsonArray.add(gid);
                    }
                }
            }
        } catch (SQLException e) {
            SystemLog.LOG(LogType.SQL_ERROR).error("查询失败", e);
            return JsonMessage.getString(100, "获取失败");
        }
        return JsonMessage.getString(200, "获取成功", jsonArray);
    }

    /**
     * 所有的类型
     *
     * @param name    名称
     * @param product 产品
     * @return stc
     */
    public String getAdType(String name, String product) {
        String tableName;
        try {
            tableName = productService.getProductTableName(name, product);
        } catch (IOException e) {
            SystemLog.ERROR().error("查询失败", e);
            return JsonMessage.getString(100, "获取失败");
        }
        if (StringUtil.isEmpty(tableName)) {
            return JsonMessage.getString(100, "没有对应产品信息");
        }
        String sql = String.format(" SELECT gid FROM %s where isDelete =0 GROUP BY gid", tableName);
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        SystemLog.LOG(LogType.SQL).info(sql);
        JSONArray jsonArray = new JSONArray();
        try {
            List<Map<String, Object>> list = JdbcUtils.executeQuery(dataSource, sql);
            if (list != null) {
                for (Map<String, Object> map : list) {
                    String gid = StringUtil.convertNULL(map.get("gid"));
                    if (StringUtil.isEmpty(gid)) {
                        gid = "默认";
                    }
                    if (!jsonArray.contains(gid)) {
                        jsonArray.add(gid);
                    }
                }
            }
        } catch (SQLException e) {
            SystemLog.LOG(LogType.SQL_ERROR).error("查询失败", e);
            return JsonMessage.getString(100, "获取失败");
        }
        return JsonMessage.getString(200, "获取成功", jsonArray);
    }

    /**
     * @param name
     * @param product
     * @return
     */
    public JSONObject getProductOperColumn(String name, String product) throws IOException {
        JSONObject jsonObject;
        try {
            jsonObject = productService.getUserProductJsonObj(name, product);
        } catch (IOException e) {
            SystemLog.ERROR().error("获取失败", e);
            return null;
        }
        if (jsonObject == null) {
            return null;
        }
        String orderType = jsonObject.getString("orderType");
        JSONObject jsonObjectType = getOrderInfo(orderType);
        if (jsonObjectType == null) {
            return null;
        }
        JSONObject operColumn = jsonObjectType.getJSONObject("operColumn");
        JSONArray htmlTable = new JSONArray();
        StringBuilder sqlColumn = new StringBuilder();
        Set<Map.Entry<String, Object>> entries = operColumn.entrySet();
        for (Map.Entry<String, Object> entry : entries) {
            JSONObject tempItem = new JSONObject();
            tempItem.put("name", entry.getKey());
            tempItem.put("desc", entry.getValue());
            sqlColumn.append(",").append(entry.getKey());
            htmlTable.add(tempItem);
        }
        JSONObject object = new JSONObject();
        object.put("columns", htmlTable);
        object.put("sqlColumn", sqlColumn.toString());
        return object;
    }

    /**
     * @param name
     * @param product
     * @return
     */
    public JSONObject getProductColumn(String name, String product) {
        JSONObject jsonObject;
        try {
            jsonObject = productService.getUserProductJsonObj(name, product);
        } catch (IOException e) {
            SystemLog.ERROR().error("获取失败", e);
            return null;
        }
        if (jsonObject == null) {
            return null;
        }
        String orderType = jsonObject.getString("orderType");
        JSONObject jsonOrder;
        try {
            jsonOrder = getOrderTypeColumnInfo(orderType);
        } catch (IOException e) {
            SystemLog.ERROR().error("获取失败", e);
            return null;
        }
        return jsonOrder;
    }


    public JSONArray getOrderType() throws IOException {
        File type = getOrderTypeConfigFile();
        return (JSONArray) JsonUtil.readJson(type.getPath());
    }

    public JSONObject getOrderInfo(String name) throws IOException {
        JSONArray jsonArray = getOrderType();
        return productService.getJSONObjectName(name, jsonArray);
    }

    /**
     * 获取表单数据信息
     *
     * @param name
     * @return
     */
    public JSONObject getOrderTypeColumnInfo(String name) throws IOException {
        JSONObject jsonObject = getOrderInfo(name);
        if (jsonObject == null) {
            return null;
        }
        JSONArray table = jsonObject.getJSONArray("table");
        JSONArray htmlTable = new JSONArray();
        StringBuilder sqlColumn = new StringBuilder();
        for (int i = table.size() - 1; i >= 0; i--) {
            JSONObject item = table.getJSONObject(i);
            String name_ = item.getString("name");
            htmlTable.add(item);
            if (sqlColumn.length() >= 1) {
                sqlColumn.append(",");
            }
            sqlColumn.append(name_);
        }
        JSONObject defaultColumn = jsonObject.getJSONObject("defaultColumn");
        if (defaultColumn != null) {
            Set<Map.Entry<String, Object>> entries = defaultColumn.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("name", entry.getKey());
                jsonObject1.put("desc", entry.getValue());
                htmlTable.add(jsonObject1);
                sqlColumn.append(",").append(entry.getKey());
            }
        }
        JSONObject object = new JSONObject();
        object.put("columns", htmlTable);
        object.put("sqlColumn", sqlColumn.toString());
        return object;
    }
}
